/**
 * Copyright (c) 2010 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.proxyserver;

import org.apache.commons.codec.binary.Base64;

public class AuthenticationProviderPopup implements iAuthenticationProvider {
  private String myAuthentication = null;
  private AuthenticationFrame myAuthenticationFrame = null;
  private int myFailCounter = 0;
  

  @Override
  public synchronized String basicAuthentication() {
    if(myAuthentication == null){
      askAuthentication();
    }
    return myAuthentication;
  }

  private void askAuthentication() {
    if(myAuthenticationFrame == null){
      myAuthenticationFrame = new AuthenticationFrame();
    }

    myAuthenticationFrame.reset();
    myAuthenticationFrame.setVisible( true );
    
    String theUserName = myAuthenticationFrame.getUserName();
    String thePassword = myAuthenticationFrame.getPassword();
    
    String theConcat = theUserName + ":" + thePassword;
    
    byte[] theEncode = Base64.encodeBase64( theConcat.getBytes() );
    
    myAuthentication = "Basic " + new String(theEncode);
  }

  @Override
  public synchronized void failedAuthentication() {
    if(myFailCounter > 0){
      myAuthentication = null;
    }
    myFailCounter++;
  }
  
  public synchronized void successfullAuthentication(){
    myFailCounter = 0;
  }

  @Override
  public String getCachedAuthentication() {
    return myAuthentication;
  }

}
